package cn.com.scan.activity;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.NumberKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import cn.com.scan.R;
import cn.com.scan.adapter.ExportItemAdapter;
import cn.com.scan.config.Config;
import cn.com.scan.entity.ApplicationItem;
import cn.com.scan.entity.ExportItem;
import cn.com.scan.jsonparser.ParseJson;
import cn.com.scan.netTools.RequestWebServive;
import cn.com.scan.netTools.ResultCode;
import cn.com.scan.tools.DialogUtils;

/**
 * Created by My on 2016/1/2.
 */
public class ExportStorageActivity extends BaseActivity {
    private String ReturnApplicationList = "ReturnApplicationList";//出库清单
    private String SubmitExpData = "SubmitExpData";//修改货数量信息
    private String SubmitExport = "SubmitExport";//确认订单信息
    private int ReturnApplicationListTAG = 100;
    private int SubmitExpDataTAG = 101;
    private int SubmitExportTAG = 102;
    private ListView listView;
    private TextView danHao,user_name,kehsi_text;
    private List<ExportItem> exportItems;
    private String APPLICATION_NO;//申领单号
    private String DEPT_NAME;//申领名称
    private String DOCUMENT_NO;//出库单号
//    private String DEPT_NAME;
    private EditText input_num;
    private boolean isScanList = false;//是否扫描过清单文件
    private Button commit_button,search_button;
    ExportItemAdapter exportIteAdapter;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            DialogUtils.closeProgressDialog();
            if (msg.what == ResultCode.SUCCESS) {
                handlerDisPose(msg);
            } else if (msg.what == ResultCode.IOFAILCODE) {
                Toast.makeText(ExportStorageActivity.this, "服务器连接失败！", Toast.LENGTH_SHORT).show();
            } else if (msg.what == ResultCode.PARSERFAILCODE) {
                Toast.makeText(ExportStorageActivity.this, "数据解析出错！", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ExportStorageActivity.this, "未知错误！", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.export_storage_activity);
        danHao = (TextView) findViewById(R.id.danhao_text);
        kehsi_text = (TextView) findViewById(R.id.kehsi_text);
        user_name = (TextView) findViewById(R.id.user_name);
        listView = (ListView) findViewById(R.id.list_view);
        input_num=(EditText)findViewById(R.id.input_num);
        search_button= (Button) findViewById(R.id.search_button);
        commit_button = (Button) findViewById(R.id.commit_button);
        search_button.setOnClickListener(onclick);
        commit_button.setOnClickListener(onclick);
        View headView = LayoutInflater.from(this).inflate(R.layout.import_storage_item, null, false);
        headView.findViewById(R.id.view_line).setVisibility(View.GONE);
        headView.setBackgroundResource(R.color.blue);
        exportIteAdapter = new ExportItemAdapter(this);
        headView.findViewById(R.id.hasnum).setVisibility(View.GONE);
        listView.addHeaderView(headView);
        listView.setOnItemLongClickListener(longClick);
        user_name.setText(user.getNAME());
    }

    private View.OnClickListener onclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.commit_button:
                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(ExportStorageActivity.this);
                    alertBuilder.setTitle("提示");
                    alertBuilder.setMessage("确定出库");
                    alertBuilder.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    arg0.dismiss();
                                    HashMap<String, Object> map = new HashMap<String, Object>();
                                    map.put("documentNo", DOCUMENT_NO);
                                    map.put("userName", user.getUSER_NAME());
                                    requestNet(SubmitExport, map, SubmitExportTAG);
                                }
                            });
                    alertBuilder.setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    arg0.dismiss();
                                }
                            });
                    alertBuilder.show();
                    break;
                case R.id.search_button:
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("documentNo", input_num.getText().toString());
                    requestNet(ReturnApplicationList, map, ReturnApplicationListTAG);
                    break;
            }

        }
    };

    @Override
    protected void broadcastExit() {
        this.finish();
    }

    @Override
    protected void capturePic(String codeStr) {
        if (isScanList) {
            requestInter(codeStr,"1",0);
        } else {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("documentNo", codeStr);
            requestNet(ReturnApplicationList, map, ReturnApplicationListTAG);
        }
    }

    public void requestNet(String method, HashMap<String, Object> map, int TAG) {
        DialogUtils.showProgressDialog(ExportStorageActivity.this);
        RequestWebServive requestWebServive = new RequestWebServive(method, handler, map, TAG);
        requestWebServive.start();
    }

    private void handlerDisPose(Message msg) {
        String str = (String) msg.obj;
        if (!TextUtils.isEmpty(str)) {
            try {
                JSONObject jsonObject = new JSONObject(str);
                int code = jsonObject.getInt("CODE");
                if (code == 0 & !TextUtils.isEmpty(str)) {
                    String RESULT = jsonObject.getString("RESULT");
                    Config.LogI("RESULT-->"+RESULT);
                    if (msg.arg1 == ReturnApplicationListTAG) {
                        Config.LogI("ReturnApplicationListTAG");
                        isScanList = true;
                        List<ApplicationItem>  appItem = ParseJson.parseApplicationItem(RESULT);
                        APPLICATION_NO = appItem.get(0).getAPPLICATION_NO();
                        DEPT_NAME = appItem.get(0).getDEPT_NAME();
                        kehsi_text.setText(DEPT_NAME);
                        danHao.setText(APPLICATION_NO);
                        exportIteAdapter.setList(null);

                    } else if (msg.arg1 == SubmitExpDataTAG) {
                        Config.LogI("SubmitExpDataTAG");
                        exportItems = ParseJson.parseExportItem(RESULT);
                        listView.setVisibility(View.VISIBLE);
                        DOCUMENT_NO = exportItems.get(0).getDOCUMENT_NO();
                        exportIteAdapter.setList(exportItems);
                        listView.setAdapter(exportIteAdapter);
                    } else if (msg.arg1 == SubmitExportTAG) {
                        Toast.makeText(ExportStorageActivity.this, "订单提交成功！", Toast.LENGTH_SHORT).show();
                        exportIteAdapter.setList(null);
                        DOCUMENT_NO="";
                        kehsi_text.setText("------------");
                        danHao.setText("------------");
                        input_num.setText("");
                    }
                } else {
                    Toast.makeText(ExportStorageActivity.this, jsonObject.getString("MSG"), Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public AdapterView.OnItemLongClickListener longClick = new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            final ExportItem im = exportItems.get(position - 1);
            final EditText et = new EditText(ExportStorageActivity.this);
            et.setKeyListener(watcher);
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(ExportStorageActivity.this);
            alertBuilder.setTitle("请输入\"" + im.getEXP_NAME() + "\"实际申领的数量");
            alertBuilder.setView(et);
            alertBuilder.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            arg0.dismiss();
                            requestInter(im.getBARCODE(), et.getText().toString(),1);
                        }
                    });
            alertBuilder.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            arg0.dismiss();
                        }
                    });
            alertBuilder.show();
            return false;
        }
    };
    //货物相关的请求
    private  void requestInter(String  val,String num,int tag){
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("appNo",APPLICATION_NO);
        map.put("barcode",val);
        map.put("quantity", num);
        map.put("ishand", tag);
        requestNet(SubmitExpData, map, SubmitExpDataTAG);
    }
    private NumberKeyListener watcher = new NumberKeyListener() {
        @Override
        public int getInputType() {
            return android.text.InputType.TYPE_CLASS_NUMBER;
        }

        @Override
        protected char[] getAcceptedChars() {
            return new char[]{'1', '2', '3', '4', '5', '6', '7', '8',
                    '9', '0', '.'};
        }
    };
}

